﻿using System.Text.RegularExpressions;

namespace ThunderboltHelper;

public class MyStringComparer: IComparer<string>
{
	public static readonly MyStringComparer Instance = new MyStringComparer();

	public static readonly string RegexNum = @"^[0-9]+";
	public static readonly string RegexHan = @"^[\u4e00-\u9fa5]+";
	public static readonly string RegexLetter = @"^[A-Za-z]+";
	public static readonly string RegexSymbol = @"^[^0-9A-Za-z\u4e00-\u9fa5]+";

	public int Compare(string x, string y)
	{
		if (double.TryParse(x, out double xd) && double.TryParse(y, out double yd))
		{
			//均由数字组成的比较
			return (int)(xd - yd);
		}
		else
		{
			bool xIsNum = Regex.IsMatch(x, RegexNum);
			bool yIsNum = Regex.IsMatch(y, RegexNum);

			bool xIsHan = Regex.IsMatch(x, RegexHan);
			bool yIsHan = Regex.IsMatch(y, RegexHan);

			bool xIsLetter = Regex.IsMatch(x, RegexLetter);
			bool yIsLetter = Regex.IsMatch(y, RegexLetter);

			bool xIsSymbol = Regex.IsMatch(x, RegexSymbol);
			bool yIsSymbol = Regex.IsMatch(y, RegexSymbol);


			if ((xIsNum && yIsNum) || (xIsHan && yIsHan) || (xIsLetter && yIsLetter) || (xIsSymbol && yIsSymbol))
			{
				//同样的字符开头，则正常比较
				return string.Compare(x, y);
			}
			else
			{
				//以数字、文字、字母、符号排序
				if (xIsNum)
				{
					return -1;
				}
				else if (yIsNum)
				{
					return 1;
				}
				else if (xIsHan)
				{
					return -1;
				}
				else if (yIsHan)
				{
					return 1;
				}
				else if (xIsLetter)
				{
					return -1;
				}
				else if (yIsLetter)
				{
					return 1;
				}
				else if (xIsSymbol)
				{
					return -1;
				}
				else if (yIsSymbol)
				{
					return 1;
				}

				return string.Compare(x, y);
			}
		}

	}
}